package com.mayikt;

/**
 * @Author: maplefire
 * @Description: 多线程之间通讯
 * @Date: 2022/08/31 18:11
 */
// 共享对象
class Res {
    public String name;
    public String sex;
}

// 写线程（生产者线程）
class WriteThread extends Thread {

    private Res res;

    public WriteThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            synchronized (res) {
                if (count == 0) {
                    res.name = "小明";
                    res.sex = "男";
                } else {
                    res.name = "小红";
                    res.sex = "女";
                }
            }
            count = (count + 1) % 2; // 这里不能用count++
        }

    }
}

// 读线程（消费者线程）
class ReadThread extends Thread {

    private Res res;

    public ReadThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                System.out.println("姓名:" + res.name + ",性别:" + res.sex);
            }
        }
    }
}

public class Test01 {

    public static void main(String[] args) {
        Res res = new Res();
        Thread write = new WriteThread(res);
        Thread read = new ReadThread(res);
        write.start();
        read.start();
    }
}
